package com.example.jussi.urldemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    EditText editText;
    Bitmap bitmap;
    String path;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0x01){
                imageView.setImageBitmap(bitmap);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        editText = (EditText) findViewById(R.id.editText);
    }

    public void showImage(View hhView){
        if("".equals(editText.getText().toString()) || editText == null){
            path = "https://b-ssl.duitang.com/uploads/item/201503/14/20150314233509_MQJ2V.thumb.700_0.jpeg";
        }else{
            path = editText.getText().toString();
        }
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL(path);
                    URLConnection connection = url.openConnection();
                    InputStream inputStream = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    handler.sendEmptyMessage(0x01);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
